package com.xauto.pioneer.appuser;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.xauto.pioneer.appuser.activity.LoginActivity;
import com.xauto.pioneer.appuser.activity.ParkingSiteActivity;
import com.xauto.pioneer.appuser.activity.mine.MineActivity;
import com.xauto.pioneer.appuser.adapter.MyFragmentPagerAdapter;
import com.xauto.pioneer.appuser.fragment.MainFragment;
import com.xauto.pioneer.appuser.fragment.ParkingFragment;
import com.xauto.pioneer.appuser.fragment.PreRentFragment;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.util.ActivityStackManager;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.util.ToastUtil;
import com.xauto.pioneer.appuser.view.NoDoubleClickListener;
import com.xauto.pioneer.appuser.view.NoScrollViewPager;
import com.xauto.pioneer.appuser.view.TopBar;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * Created by Administrator on 2018/5/12.
 */

public class MainActivity extends FragmentActivity{

    /**
     * 主界面，3个fragment装到一个viewpager中切换
     */
    // 主界面控件引用 3frag切换，一个viewpager
    @Bind(R.id.main_viewpager)
    NoScrollViewPager main_Pager;
    @Bind(R.id.topBar)
    TopBar topBar;
    @Bind(R.id.tv_first)
    TextView tv_first;
    @Bind(R.id.tv_second)
    TextView tv_second;
    @Bind(R.id.tv_third)
    TextView tv_third;
    @Bind(R.id.ll_first)
    LinearLayout ll_first;
    @Bind(R.id.ll_second)
    LinearLayout ll_second;
    @Bind(R.id.ll_third)
    LinearLayout ll_third;


    ArrayList<Fragment> fragmentList;
    MyFragmentPagerAdapter adapterF;
    Fragment fragMain,fragAdvanceRent,fragParking;
    public FragmentManager fragmentManager;
    public String curFragmentTag = "";
    // 当前页卡编号
    public int currIndex = 0;
    Context mContext;
    boolean permissioned = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityStackManager.getActivityManager().push(this);
        mContext = this;
        setContentView(R.layout.ac_tab);
        ButterKnife.bind(this);
        initData();
    }

    protected void initData() {
        showLocationPremission();
    }
    protected void initView() {
        topBar.showView(TopBar.TITLE, TopBar.LEFT_IMAGE_BTN, TopBar.RIGHT_TV_BTN);
        topBar.setText(TopBar.TITLE, R.string.top_bar_home);
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_top_bar_left);
//        topBar.setImage(TopBar.RIGHT_IMAGE_BTN, R.mipmap.ic_top_bar_refresh);
        topBar.setText(TopBar.RIGHT_TV_BTN,"网点");
        topBar.setLeftOnClick(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                //跳转个人中心
                if (!isLoginSuccess()) {
                    //未登录跳转登录页面
                    startActivity(new Intent(mContext, LoginActivity.class));
                    return;
                }
                topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_top_bar_left);
                startActivity(new Intent(mContext, MineActivity.class));
            }
        });
        topBar.setRightOnClick(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                //选择取车网点
                if (MainFragment.bdLocation != null){
                    MainFragment.popDismiss();
                    Intent intent = new Intent(mContext, ParkingSiteActivity.class);
                    intent.putExtra("longitude", String.valueOf(MainFragment.currentLatLng.longitude));
                    intent.putExtra("latitude", String.valueOf(MainFragment.currentLatLng.latitude));
                    intent.putExtra("distance", String.valueOf(MainFragment.MapCurrentDistanceList));
                    startActivityForResult(intent,100);
                }else {
                    prompt("当前位置不可用，请先刷新界面");
                }
            }
        });
        initViewPager();
        addListener();
    }
    // 初始化viewpager，将3个frag添加到
    public void initViewPager() {
        fragMain = new MainFragment();
        fragParking = new ParkingFragment();
        fragAdvanceRent = new PreRentFragment();
        fragmentList = new ArrayList<Fragment>();
        fragmentList.add(fragMain);
        fragmentList.add(fragParking);
        fragmentList.add(fragAdvanceRent);
        // 给ViewPager设置适配器
        adapterF = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        main_Pager.setAdapter(adapterF);
        main_Pager.setCurrentItem(0, false);// 设置当前显示标签页为第一页
        ll_first.setSelected(true);
        tv_second.setSelected(false);
        tv_third.setSelected(false);
        main_Pager.setOnPageChangeListener(new MyOnPageChangeListener());// 页面变化时的监听器
        main_Pager.setOffscreenPageLimit(2);
        main_Pager.setScanScroll(false);
    }

    /**
     * 添加监听器
     */
    private void addListener() {
        ll_first.setOnClickListener(new tvListener(0));
        ll_second.setOnClickListener(new tvListener(1));
        ll_third.setOnClickListener(new tvListener(2));
    }
    // tv点击监听器，传当前指引，切换viewpager
    public class tvListener implements View.OnClickListener {
        private int index = 0;

        public tvListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            main_Pager.setCurrentItem(index);
        }
    }

    //点击父activity网点按钮刷新回调子fragment弹窗
    static ParkingSiteCallback callback;
    public void setCallback(ParkingSiteCallback callback){
        this.callback = callback;
    }
    public interface ParkingSiteCallback{
         void setdata(int resultCode, int requestCode,Intent data);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        Log.e("TAG","resultcode0 = "+resultCode+" , requestCode = "+requestCode);
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(intentResult != null) {
            if(intentResult.getContents() == null) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Scanned: " + intentResult.getContents(), Toast.LENGTH_LONG).show();

            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
        if (resultCode == Activity.RESULT_OK && requestCode == 100){

            if(callback!=null){
                callback.setdata(resultCode,requestCode,data);
            }
        }
    }
    /**
     * 监听viewpager状态改变按钮状态
     */
    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            // 改变pager后设置颜色标记
            currIndex = position;
            if (currIndex == 0) {
                ll_first.setSelected(true);
                tv_second.setSelected(false);
                tv_third.setSelected(false);
            }
            if (currIndex == 1) {
                ll_first.setSelected(false);
                tv_second.setSelected(true);
                tv_third.setSelected(false);
                MainFragment.popDismiss();
            }
            if (currIndex == 2) {
                ll_first.setSelected(false);
                tv_second.setSelected(false);
                tv_third.setSelected(true);
                MainFragment.popDismiss();
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }


    /***
     * login status
     * @return true-login_success | false-no login_success
     */
    protected boolean isLoginSuccess() {
        if(!StringUtils.isBlank(PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID))
                &&!StringUtils.isBlank(PreferencesUtils.getString(mContext, Constants.KEY_TOKEN))) {
            return true;
        }
        return false;
    }

    /***
     * TOAST
     * @param msg
     */
    protected void prompt(String msg) {
        if(mContext != null) {
            ToastUtil.showShort(mContext, msg);
        }
    }
    /**
     * 请求位置访问权限
     */
    public void showLocationPremission(){
        if (Build.VERSION.SDK_INT>=23){
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED)
            {
                ToastUtil.showShort(mContext,"没有权限,请手动开启定位权限");
                // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_PHONE_STATE,
                        android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 100);
            }else{
//                initBaiDuMap();
                initView();
            }
        }else{
            initView();
//            initBaiDuMap();
        }
    }
    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 100:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    initView();
                } else {
                    // 没有获取到权限，做特殊处理
                    MainActivity.this.finish();
                    ToastUtil.showShort(mContext,"获取位置权限失败，请手动开启");
                }
                break;
            default:
                break;
        }
    }
    @Override
    public void onBackPressed() {
        KeyBackQuit(KeyEvent.KEYCODE_BACK);
    }
    private boolean isQuit = false;
    private Timer timer = new Timer();
    public boolean KeyBackQuit(int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isQuit == false) {
                isQuit = true;
                Toast.makeText(getBaseContext(), getResString(R.string.text_quit),
                        Toast.LENGTH_SHORT).show();
                TimerTask task = null;
                task = new TimerTask() {
                    @Override
                    public void run() {
                        isQuit = false;
                    }
                };
                timer.schedule(task, 2000);
            } else {
                ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                manager.killBackgroundProcesses(getPackageName());
                finish();
//				System.exit(0);
            }
        }
        return isQuit;
    }

    protected String getResString(int StringId) {
        return mContext.getResources().getString(StringId);
    }
}
